<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 邮件函数库
 * 
 * @desc 
 * @version 1.0.0 
 * @author  Jason
 * @date    2017年4月28日 上午10:38:44
 */
class Lib_email
{
	
	/** @var CI_Controller */
	private $CI;
	
	/** @var CI_Email */
	private $email = null;
	
	public function __construct()
	{
		$this->CI =& get_instance();
	
		$this->CI->load->library('email');
		$this->email =& $this->CI->email;
	}
	
	public function send_recovery_email($to, $data)
	{
		$subject = 'passport recovery';
		$format = "click %s to recovery password!";
		$body = sprintf($format, $data['url']);
		// 以下设置Email内容
		// service@segway.com
		$this->CI->config->load('email');
		$from = $this->CI->config->item('smtp_user');
		$return = $from;
		$back = 'service.discovery@segway.com';
		$this -> CI -> email -> from($from, 'Service.Discovery', $return);
		$this -> CI -> email -> to($to);
		$this -> CI -> email -> subject($subject);
		$this -> CI -> email -> message($body);
		// $this->CI->email->attach('application\controllers\1.jpeg'); //相对于index.php的路径
		$result = false;
		try {
			/*
			<h4>A PHP Error was encountered</h4>
			<p>Severity: Warning</p>
			<p>Message:  fsockopen(): unable to connect to ssl://smtp.126.com:465 (Connection timed out)</p>
			<p>Filename: libraries/Email.php</p>
			<p>Line Number: 2063</p>
			 */
			// php error 捕获
			// 在实际开发中，错误及异常捕捉仅仅靠try{}catch()是远远不够的。
			// See To: http://blog.csdn.net/e421083458/article/details/8157154
			$result = $this -> CI -> email -> send();
		} catch (ErrorException $e) {
			// not catched!
			var_dump($e);
		} catch (Exception $e) {
			// not catched!
			var_dump($e);
		}
		if (!$result) {
			$status = false;
			// 返回一个包含了所有的服务器信息、Email 头部信息、以及 Email 正文信息的字符串。用于调试。
			// echo $this -> CI -> email -> print_debugger();
			// 你可以指定只返回消息的哪个部分，有效值有：headers 、 subject 和 body 。
			$headers = $this -> CI -> email -> print_debugger(['headers']);
			$subject = $this -> CI -> email -> print_debugger(['subject']);
			$body = $this -> CI -> email -> print_debugger(['body']);
			
			// log_message($level, $message)
			// 该函数用于向你的日志文件中写入信息
			// 信息级别 = 调试，错误和一般信息, 信息本身 = 信息本身
			// See To: 错误处理 - https://codeigniter.org.cn/user_guide/general/errors.html?highlight=log#id1
			log_message('error', PHP_EOL . str_repeat('-', 75) . ">" . PHP_EOL
					. $headers . PHP_EOL . "<" . str_repeat('-', 75) . PHP_EOL);
			
			log_message('error', PHP_EOL . str_repeat('-', 75) . ">" . PHP_EOL
					. $subject . PHP_EOL . "<" . str_repeat('-', 75) . PHP_EOL);
			
			log_message('error', PHP_EOL . str_repeat('-', 75) . ">" . PHP_EOL
					. $body . PHP_EOL . "<" . str_repeat('-', 75) . PHP_EOL);
			
		} else {
			$status = true;
		}
		
		return $status;
	}
}